package picturetaker.application;

import java.net.MalformedURLException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import picturetaker.persistence.ImageManager;
import picturetaker.utility.MyXMLReader;
import picturetaker.domain.Camera;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class AppCore implements Job {
	
	public AppCore() {
	}

	private void init()  throws MalformedURLException {
		List<Camera> cameras = initCameras();
		new Thread(new MainThread(cameras)).start();
	}

	public static List<Camera> initCameras() throws MalformedURLException {
		try {
			List<Camera> cameras = MyXMLReader.readConfiguration();
			ImageManager manager = ImageManager.getInstance();
			List<Camera> configuredCameras = manager.getAllCameras();
			if (!configuredCameras.containsAll(cameras)) {
				List<Camera> temp = new ArrayList<Camera>(cameras);
				temp.removeAll(configuredCameras);
				manager.insertCameras(temp);
				setCameraIds(cameras, manager.getAllCameras());
			} else {
				setCameraIds(cameras, configuredCameras);
			}
			if (cameras.isEmpty())
				return null;
			return cameras;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void setCameraIds(List<Camera> cameras,
			List<Camera> configuredCameras) {
		for (Camera camera : cameras) {
			camera.setId(configuredCameras.get(
					configuredCameras.indexOf(camera)).getId());
		}
	}

    public void execute(JobExecutionContext context) throws JobExecutionException {
    	try {
    		AppCore core = new AppCore();
    		core.init();
    	} catch (Exception e) {
    		e.printStackTrace();
        }
    	
    }

}
